package com.demo.listener;

import com.demo.model.Address;
import com.demo.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 事件监听类，监听事务提交操作
 */
@Slf4j
@Component
public class ApplicationEventListener {

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void afterCommitForUser(PayloadApplicationEvent<User> event) throws InterruptedException {
        Thread.sleep(5000L);
        log.info("ApplicationEventListener userId = {}", event.getPayload().getUserId());
    }

    /**
     * 监听Addres对象保存到数据库并且提交事务后操作，建议配合@Async注解使用，用异步线程进行监听操作
     * @param event
     * @throws InterruptedException
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void afterCommitForAddress(PayloadApplicationEvent<Address> event) throws InterruptedException {
        Thread.sleep(5000L);
        log.info("ApplicationEventListener id = {}", event.getPayload().getId());
    }
}
